package com.dronff.handler;


import com.dronff.parser.TangProtocolParser;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * TangRPC支持使用多种通信协议进行远程调用，TangProtocolInvokerHandler
 * |--------|-----------|
 * |置零字节 | 总长度4字节 |
 */
public class ProtocolSelectHandler extends ByteToMessageDecoder {
    static final Logger logger = Logger.getLogger(ProtocolSelectHandler.class);

    private TangProtocolParser tangProtocolParser = new TangProtocolParser();
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf == null || byteBuf.readableBytes() == 0) {
            logger.debug("没有可以读取的字节");
        }
        assert byteBuf != null;
        if (byteBuf.getByte(0) == 0) {
            logger.debug("当前连接采用协议为：自定义协议");
            list.add(tangProtocolParser.parseBytes(byteBuf));
        }else{
            logger.debug("当前连接采用协议为：HTTP协议");
            ByteBuf copy = byteBuf.copy();
            byteBuf.clear();
            list.add(copy);
        }
    }

}
